package com.sjm.demo.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.sjm.demo.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Slf4j
@Component
public class SmsUtil {

    private static SmsProperties properties;

    @Autowired
    public void setSmsProperties(SmsProperties prop){
        SmsUtil.properties = prop;
    }

    private static final String domain = "dysmsapi.aliyuncs.com";

    public CommonResponse sendSms(String phone, String code)  {
        System.out.println(properties+phone+code);

        //设置超时时间-可自行调整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        DefaultProfile profile = DefaultProfile.getProfile("default", properties.getAccessKeyId(), properties.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(domain);

        request.setVersion("2017-05-25");

        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-shanghai");

        //必填:待发送手机号
        request.putQueryParameter("PhoneNumbers", phone);
        //必填:短信签名-可在短信控制台中找到
        request.putQueryParameter("SignName", properties.getSignName());
        //必填:短信模板-可在短信控制台中找到
        request.putQueryParameter("TemplateCode", properties.getVerifyCodeTemplate());

        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");

        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("发送短信结果为：{}",response.getData());
            return response;
        } catch (ServerException e) {
            log.error("服务异常：{}",e.getMessage());
        } catch (ClientException e) {
            log.error("客户端异常：{}",e.getMessage());
        }
        return null;
    }
}